<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理 </el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card style="margin-top: 15px">
      <!-- 添加角色 -->
      <el-row>
        <el-col>
          <el-col>
            <el-button type="primary" @click="dialogVisible = true"
              >添加角色</el-button
            >
          </el-col>
        </el-col>
      </el-row>
      <!-- 角色列表 -->
      <el-table
        :data="roleList"
        style="width: 100%; margin-top: 15px"
        border
        stripe
      >
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdtop', i1 === 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="delRights(scope.row, scope.row.id)">{{
                  item1.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级权限 -->
              <el-col :span="19">
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="delRights(scope.row, scope.row.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="danger"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="delRights(scope.row, scope.row.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roledes" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button
              type="primary"
              class="el-icon-edit"
              @click="editRole(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              class="el-icon-delete"
              @click="delRole(scope.row.id)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-button
              type="warning"
              class="el-icon-setting"
              @click="showSetRight(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色 对话框-->
    <el-dialog
      title="添加角色"
      :visible.sync="dialogVisible"
      @close="dialogClose"
    >
      <el-form
        ref="addRoleRef"
        :model="addRoleForm"
        label-width="80px"
        :rules="addRoleRules"
      >
        <el-form-item label="角色名称" prop="rolename">
          <el-input v-model="addRoleForm.rolename"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roledes">
          <el-input v-model="addRoleForm.roledes"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="dialogVisible"
      @close="dialogClose"
    >
      <el-form
        ref="aditRoleRef"
        :model="aditRoleForm"
        label-width="80px"
        :rules="addRoleRules"
      >
        <el-form-item label="角色名称" prop="rolename">
          <el-input v-model="aditRoleRef.rolename"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roledes">
          <el-input v-model="aditRoleRef.roledes"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="dialogVisible"
      width="50%"
      @click="setRightsClose"
    >
      <el-tree
        :data="rightList"
        :props="defaultProps"
        lazy
        show-checkbox
        node-key="id"
        default-expand-all
        :default-expanded-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      roleList: [
        {
          id: 30,
          roleName: '主管',
          roledes: '技术负责人',
          children: [
            {
              id: 31,
              authName: '商品管理',
              path: 'goods',
              children: [
                {
                  id: 310,
                  authName: '商品列表',
                  path: null,
                  children: [{ id: 319, authName: '添加商品', path: null }],
                },
                {
                  id: 308,
                  authName: '分类参数',
                  path: null,
                  children: [
                    { id: 319, authName: '获取列表参数', path: null },
                    { id: 317, authName: '创建商品参数', path: null },
                  ],
                },
              ],
            },
            {
              id: 34,
              authName: '订单管理',
              path: 'goods',
              children: [
                {
                  id: 314,
                  authName: '订单列表',
                  path: null,
                  children: [{ id: 320, authName: '订单参数', path: null }],
                },
              ],
            },
          ],
        },
      ],
      dialogVisible: false,
      // 添加角色数据
      addRoleForm: {
        rolename: '',
        roledes: '',
      },
      // 添加角色规则
      addRoleRules: {
        rolename: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
        ],
        roledes: [
          { required: true, message: '请添加角色描述', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
        ],
      },
      // 编辑角色
      aditRoleForm: {},
      // 编辑角色规则
      aditRoleRef: {
        rolename: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
        ],
        roledes: [
          { required: true, message: '请添加角色描述', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
        ],
      },
      // 分配权限对话框
      rightList: [],
      // 树形控件
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      // 选中的三级权限
      defKeys: [],
    }
  },
  created() {
    // this.getRoleList()
  },
  methods: {
    // 获取角色列表数据
    async getRoleList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.roleList = res.data
    },
    // 添加角色按钮
    addRoles() {
      this.$refs.addRoleRef.validate(async (valid) => {
        // 校验是否合法
        if (!valid) return
        const { data: res } = await this.$http.post('roles')
        if (res.meta.status !== 200) {
          this.$message.error('添加角色失败')
        }
        this.$message.success('添加角色成功')
        this.dialogVisible = false
        this.getRoleList()
      })
    },
    // 监听对话框关闭时 清空数据
    dialogClose() {
      this.$refs.addRoleRef.resetFields()
    },
    // 编辑角色按钮
    async editRole(id) {
      this.dialogVisible = true
      const { data: res } = await this.$http.get('roles/+id')
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户列表失败')
      }
      this.aditRoleForm = res.data
      this.dialogVisible = false
    },
    // 删除角色
    async delRole(id) {
      const del = await this.$confirm(
        '此操作将永久删除该用戶, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      // 刪除 确认    放回字符串confirm
      // 刪除 取消    放回字符串cancel
      if (del !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('user/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败')
      }
      this.$message.success('删除用户成功')
      this.getUserList()
    },
    // 删除三级权限
    async delRights(role, id) {
      const del = await this.$confirm(
        '此操作将永久删除该用戶, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      // 刪除 确认    放回字符串confirm
      // 刪除 取消    放回字符串cancel
      if (del !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      // this.getRoleList()
      // 保留页面不退出
      role.children = res.data
    },
    // 展示分配权限的对话款
    async showSetRight(role) {
      const { data: res } = await this.$http.get('right/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败')
      }
      this.rightList = res.data
      // 递归获取三级节点
      this.getLeafKeys(role, this.getLeafKeys)
      this.dialogVisible = false
    },
    // 通过递归的形式 获取角色所有三级权限的id
    getLeafKeys(node, arr) {
      if (!node.children) {
        return
      }
      node.children.forEach((item) => {
        this.getLeafKeys(item.arr)
      })
    },
    // 监听分配权限对话款的关闭事件
    setRightsClose() {
      this.defKeys = []
    },
    // 点击为角色分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedNodes(),
        ...this.$refs.treeRef.getCheckedKeys(),
      ]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(
        // 'roles/${this,roledId}/rights',
        { rids: idStr }
      )
      if (res.meta.status !== 200) {
        return this.$message.err('分配角色失败')
      }
      this.$message.success('分配角色成功')
      this.getRoleList()
    },
  },
}
</script>
<style scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
